const router = require("express").Router();
const fs = require("fs");
const path = require("path");
const multiparty = require("multiparty");
const randomstring = require("randomstring");
const oauth = require("../uploadyandex/oauthmanage");
const axios = require("axios").default;
const https = require("https");
const url = require("url");
const Debug = require("debug");
const dbg = Debug("Ya-write-uploadtest");
dbg.enabled = true;
const app = require("../../app-real");


let mntpath = path.join(__dirname, "..", "..", "mnt");
if (!fs.existsSync(mntpath)) {
    fs.mkdirSync(mntpath);
}

// router.use("/socketio",SocketIOFileUpload.router);
router.use("/socket.html", function (req, res) {
    fs.createReadStream(path.join(__dirname, "./socket.html")).pipe(res);
});

router.get("/chunk.html", function (req, res) {
    if (req.originalUrl.endsWith("/")) {
        res.redirect(
            req.originalUrl.replace(/\/$/, "")
        );
    } else {
        fs.createReadStream(path.join(__dirname, "./chunk.html")).pipe(res);
    }

});


router.post("/chunk", (req, res) => {
    let uploadid = req.query['uploadid'];
    if (upid_record[uploadid]) {
        let part = req.query['part'];
        let form = new multiparty.Form({
            uploadDir: path.join(mntpath, `pieces-${uploadid}`)
        });
        form.parse(req, function (err, fileds, files) {
            if (err) {
                res.send(500, { err: err.message });
            } else {
                let fileindisk = files['chunk-file'][0];
                upid_record[uploadid].files[part] = fileindisk;
                res.send({ success: true, debug: upid_record[uploadid] });
            }
        })
    } else {
        res.send(404, "No such uploadid");
    }
});
const upid_record = {};
router.get("/chunk/uploadid", (req, res) => {
    let filename = req.query['name'];
    let filesize = req.query['size'];
    let filetype = req.query['type'];
    let uploadid = randomstring.generate(5);
    let piecedirpath = path.join(mntpath, `pieces-${uploadid}`);
    fs.mkdir(piecedirpath, (err) => {
        if (err) {
            res.send(500, err.message);
        } else {
            upid_record[uploadid] = { filename, filesize, filetype, files: [] };
            res.send({ uploadid });
        }
    })

});

router.get("/chunk/finish", (req, res) => {
    let uploadid = req.query['uploadid'];
    if (upid_record[uploadid]) {
        let record = upid_record[uploadid];
        let realname = record.filename;
        (function uploadToYandex() {
            let TOKEN = oauth.getToken();
            axios.get(`https://cloud-api.yandex.net/v1/disk/resources/upload?path=${encodeURIComponent(
                `app:/${randomstring.generate(5)}.${realname}`
            )}`, {
                    headers: {
                        Authorization: `OAuth ${TOKEN}`
                    }
                }).then(axios_resp => {
                    let d = axios_resp.data;
                    dbg("%j", d);
                    let href = d['href'];
                    dbg("upload href is ", href);
                    let parsedHref = url.parse(href);
                    let request = https.request({
                        method: d['method'],
                        hostname: parsedHref.hostname,
                        path: parsedHref.path
                    }, (httpRes) => {
                        console.log("-----");
                        dbg("headers-->");
                        dbg("%j", httpRes.headers);
                        dbg("status code ", httpRes.statusCode, httpRes.statusMessage)
                        // httpRes.pipe(process.stderr);
                    });
                    let index = 0;
                    let fileRead;
                    (function transferPieces() {
                        fileRead = fs.createReadStream(
                            record.files[index].path
                        );
                        fileRead.on("data",(chunk)=>{
                            process.stderr.write(`[${record.files[index].path}]write`);
                            request.write(chunk);
                        });
                        fileRead.on("close",()=>{
                            dbg(`[${index}th]stream end`);
                            index++;
                            if(index<record.files.length){
                                transferPieces();
                            }else{
                                dbg("transfer end");
                                request.end();
                            }
                        })

                    })();
                })
        })();
        res.send("Let yandex to reiceve ,"+ realname);
    } else {
        res.send(404, "No such uploadid");
    }
})

router.get("/", (req, res) => {
    res.render("uploadtest", {
        title: "use FormData to upload...",
        uploadhref: "/uploadtest"
    })
});

router.post("/raw", (req, res) => {
    let fstream = fs.createWriteStream(path.join(mntpath, "raw.file"));
    fstream.on("close", () => {
        res.send("ok");
    });
    req.pipe(fstream);
})
router.post("/", (req, res) => {
    let form = new multiparty.Form({
        uploadDir: mntpath
    });
    form.parse(req, function (err, fileds, files) {
        if (err) {
            res.send(500, { err: err.message });
        } else {
            res.send({ fileds, files });
        }
    })
    // req.pipe(filestream);
})

module.exports = router;